package com.dxy.md.config;

import com.dxy.md.core.CustomRoutingDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.boot.autoconfigure.MybatisProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.util.StringUtils;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
@MapperScan("com.dxy.md.user.mapper") // 配置mybatis的Mapper扫描路径（这也是要用mybatis-spring-boot-starter的原因）
@EnableConfigurationProperties({MybatisProperties.class}) // 由于排除了 MybatisAutoConfiguration，所以此处要收入导入MybatisProperties类
public class MyBatisConfig {

    @Autowired
    private MybatisProperties mybatisProperties;

    /**
     * master数据源
     */
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.master")
    public DataSource masterDataSource() {
        return DataSourceBuilder.create().build();
    }

    /**
     * slave数据源
     */
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.slave")
    public DataSource slaveDataSource() {
        return DataSourceBuilder.create().build();
    }

    /**
     * 虚拟路由数据源
     */
    @Bean
    public DataSource routingDataSource() {
        AbstractRoutingDataSource routingDataSource = new CustomRoutingDataSource();
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put("master", masterDataSource());
        targetDataSources.put("slave", slaveDataSource());
        // 目标数据源Map
        routingDataSource.setTargetDataSources(targetDataSources);
        // 默认数据源
        routingDataSource.setDefaultTargetDataSource(masterDataSource());
        return routingDataSource;
    }

    /**
     * 显式配置SqlSessionFactory（主要要在启动类中排除 MybatisAutoConfiguration）
     */
    @Bean
    public SqlSessionFactory sqlSessionFactoryBean() throws Exception {
        SqlSessionFactoryBean factory = new SqlSessionFactoryBean();
        factory.setDataSource(routingDataSource());
        // 应用所有mybatis配置
        factory.setMapperLocations(
                mybatisProperties.resolveMapperLocations());

        if (StringUtils.hasText(mybatisProperties.getTypeAliasesPackage())) {
            factory.setTypeAliasesPackage(
                    mybatisProperties.getTypeAliasesPackage());
        }

        if (mybatisProperties.getConfiguration() != null) {
            factory.setConfiguration(
                    mybatisProperties.getConfiguration());
        }
        return factory.getObject();
    }

    // 配置事务管理器
    @Bean
    public PlatformTransactionManager transactionManager() {
        return new DataSourceTransactionManager(routingDataSource());
    }

}
